package com.lemon.funplus.ulti;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.content.pm.Signature;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.provider.MediaStore.Images;
import android.util.Base64;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.View.MeasureSpec;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.Toast;

@SuppressLint("NewApi")
public class BaseEngine {

	@SuppressWarnings("unused")
	public static String BitmapTobase64(Bitmap bm) {

		 BitmapFactory.Options options = new BitmapFactory.Options();
		 options.inDither = false;
		 options.inJustDecodeBounds = false;
		 options.inPreferredConfig = Bitmap.Config.ARGB_8888;
		 options.inSampleSize = 1;
		 options.inPurgeable = true;
		 options.inPreferQualityOverSpeed = true;
		 options.inTempStorage=new byte[32 * 1024];
		
		 ByteArrayOutputStream stream = new ByteArrayOutputStream();
		 bm.compress(Bitmap.CompressFormat.JPEG, 80, stream);
		 byte[] bytes = stream.toByteArray();
		 String encodedImage = Base64.encodeToString(bytes,Base64.DEFAULT);
		/*
	     * 
	     * 
	     * */
		// ByteArrayOutputStream baos = new ByteArrayOutputStream();
		// bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
		// byte[] byteArrayImage = baos.toByteArray();
		// String encodedImage = Base64.encodeToString(byteArrayImage,
		// Base64.DEFAULT);
		 return encodedImage;
		/*
	     * 
	     * 
	     * */
//		ByteArrayOutputStream baos = new ByteArrayOutputStream();
//		bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
//		byte[] b = baos.toByteArray();
//		String temp = null;
//		try {
//			System.gc();
//			temp = Base64.encodeToString(b, Base64.DEFAULT);
//		} catch (Exception e) {
//			e.printStackTrace();
//		} catch (OutOfMemoryError e) {
//			baos = new ByteArrayOutputStream();
//			bm.compress(Bitmap.CompressFormat.JPEG, 50, baos);
//			b = baos.toByteArray();
//			temp = Base64.encodeToString(b, Base64.DEFAULT);
//			Log.e("EWN", "Out of memory error catched");
//		}
//		return temp;
	}

	public static Bitmap BitmapFromBase64(String input) {
		byte[] decodedByte = Base64.decode(input, 0);
		return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
	}

	public static boolean checkVinaPhone(String number) {
		// if(number.startsWith("091")&&number.length()==10)
		// return true;
		// if(number.startsWith("094")&&number.length()==10)
		// return true;
		// if(number.startsWith("0123")&&number.length()==11)
		// return true;
		// if(number.startsWith("0124")&&number.length()==11)
		// return true;
		// if(number.startsWith("0125")&&number.length()==11)
		// return true;
		// if(number.startsWith("0127")&&number.length()==11)
		// return true;
		// if(number.startsWith("0129")&&number.length()==11)
		return true;
		// return false;
	}

	public static String checkUrlPath(String path) {
		return path.replaceAll(" ", "%20");
	}

	public static boolean isConnectionAvailable(Context context) {
		ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivityManager != null) {
			NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo();
			if (netInfo != null && netInfo.isConnected() && netInfo.isConnectedOrConnecting() && netInfo.isAvailable()) {
				return true;
			}
		}
		return false;
	}

	public static void shareTextUrl(Context context, String name, String url) {
		Intent share = new Intent(android.content.Intent.ACTION_SEND);
		share.setType("text/plain");
		share.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
		share.putExtra(Intent.EXTRA_SUBJECT, name);
		share.putExtra(Intent.EXTRA_TEXT, url);
		context.startActivity(Intent.createChooser(share, "Share link!"));
	}

	// public static void shareBitmap(Context context, Bitmap bitmap) {
	// String pathofBmp = Images.Media.insertImage(context.getContentResolver(),
	// bitmap, "title", null);
	// Uri bmpUri = Uri.parse(pathofBmp);
	// Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
	// shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
	// shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
	// shareIntent.setType("image/png");
	// context.startActivity(Intent.createChooser(shareIntent, "Share!"));
	// }
	public static void shareBitmap(Context context, Bitmap bitmap) {
		// String pathofBmp =
		// Images.Media.insertImage(context.getContentResolver(), bitmap,
		// "title", null);
		// Uri bmpUri = Uri.parse(pathofBmp);
		// Share(context,getShareApplication(), bmpUri);
		shareTextUrl(context, "Tử vi 360", "http://tuvi360.vn/");
	}

	private static List<String> getShareApplication() {
		List<String> mList = new ArrayList<String>();
		mList.add("com.facebook.katana");
		mList.add("com.twitter.android");
		mList.add("com.google.android.gm");
		mList.add("com.zing.zalo");
		return mList;

	}

	@SuppressLint("DefaultLocale")
	private static void Share(Context context, List<String> PackageName, Uri bmpUri) {
		try {
			List<Intent> targetedShareIntents = new ArrayList<Intent>();
			Intent share = new Intent(android.content.Intent.ACTION_SEND);
			share.setType("image/png");
			List<ResolveInfo> resInfo = context.getPackageManager().queryIntentActivities(share, 0);
			if (!resInfo.isEmpty()) {
				for (ResolveInfo info : resInfo) {
					Intent targetedShare = new Intent(android.content.Intent.ACTION_SEND);
					targetedShare.setType("image/png");
					if (PackageName.contains(info.activityInfo.packageName.toLowerCase())) {
						targetedShare.putExtra(Intent.EXTRA_STREAM, bmpUri);
						targetedShare.setPackage(info.activityInfo.packageName.toLowerCase());
						targetedShareIntents.add(targetedShare);
					}
				}
				try {
					Intent intent = new Intent(Intent.ACTION_SEND);
					intent.setData(bmpUri);
					intent.setPackage("com.google.android.apps.plus");
					targetedShareIntents.add(intent);
				} catch (Exception e) {
					Log.e("PlusShare", "PlusShare" + e.toString());
					e.printStackTrace();
				}
				Intent chooserIntent = Intent.createChooser(targetedShareIntents.remove(0), "Share");
				chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetedShareIntents.toArray(new Parcelable[] {}));
				context.startActivity(chooserIntent);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void shareBitmap(Context context, Bitmap bitmap, String url) {
		String pathofBmp = Images.Media.insertImage(context.getContentResolver(), bitmap, "title", null);
		Uri bmpUri = Uri.parse(pathofBmp);
		Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
		shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
		shareIntent.putExtra(Intent.EXTRA_TEXT, url);
		shareIntent.setType("*/*");
		context.startActivity(Intent.createChooser(shareIntent, "Share!"));
	}

	@TargetApi(Build.VERSION_CODES.FROYO)
	public static final void getKeyHashes(Context context) {
		PackageInfo packageInfo;
		try {
			// packageInfo =
			// getPackageManager().getPackageInfo("casino.vn",PackageManager.GET_SIGNATURES);
			packageInfo = context.getPackageManager().getPackageInfo(context.getPackageManager().getPackageInfo(context.getPackageName(), 0).packageName,
					PackageManager.GET_SIGNATURES);
			for (Signature signature : packageInfo.signatures) {
				MessageDigest md = MessageDigest.getInstance("SHA");
				md.update(signature.toByteArray());
				String key = new String(Base64.encode(md.digest(), 0));
				// String key = new String(Base64.encodeBytes(md.digest()));
				Log.e("Hash key", key);
			}
		} catch (NameNotFoundException e1) {
			Log.e("Name not found", e1.toString());
		} catch (NoSuchAlgorithmException e) {
			Log.e("No such an algorithm", e.toString());
		} catch (Exception e) {
			Log.e("Exception", e.toString());
		}
	}

	public static void sendSMS(Context context, String phoneNumber, String message) {
		Log.i("Send SMS", "");
		Intent smsIntent = new Intent(Intent.ACTION_VIEW);
		smsIntent.setType("vnd.android-dir/mms-sms");
		// smsIntent.setData(Uri.parse("smsto:"));
		smsIntent.putExtra("address", phoneNumber);
		smsIntent.putExtra("sms_body", message);
		try {
			context.startActivity(smsIntent);
			Log.i("Finished sending SMS...", "");
		} catch (android.content.ActivityNotFoundException ex) {
			Toast.makeText(context, "SMS faild, please try again later.", Toast.LENGTH_SHORT).show();
		}
	}

	public static void sendSMS(Context context, String message) {
		Log.i("Send SMS", "");
		Intent smsIntent = new Intent(Intent.ACTION_VIEW);
		smsIntent.setType("vnd.android-dir/mms-sms");
		// smsIntent.setData(Uri.parse("smsto:"));
		smsIntent.putExtra("sms_body", message);
		try {
			context.startActivity(smsIntent);
			Log.i("Finished sending SMS...", "");
		} catch (android.content.ActivityNotFoundException ex) {
			Toast.makeText(context, "SMS faild, please try again later.", Toast.LENGTH_SHORT).show();
		}
	}

	public static void showLogformLongString(String _tag, String str) {
		String tag = "GetJson";
		if (_tag != null && !_tag.equals("")) {
			tag = _tag;
		}
		if (str != null)
			if (str.length() > 4000) {
				Log.e(tag, "str.length = " + str.length());
				int chunkCount = str.length() / 4000; // integer division
				for (int i = 0; i <= chunkCount; i++) {
					int max = 4000 * (i + 1);
					if (max >= str.length()) {
						Log.e(tag, "chunk " + i + " of " + chunkCount + ":" + str.substring(4000 * i));
					} else {
						Log.e(tag, "chunk " + i + " of " + chunkCount + ":" + str.substring(4000 * i, max));
					}
				}
			} else {
				Log.e(tag, str.toString());
			}
	}

	@SuppressWarnings("deprecation")
	public static Bitmap ConvertViewtoBitmap(Context context, View view) {
		Paint paint = new Paint();
		Display display = ((Activity) context).getWindowManager().getDefaultDisplay();
		int width = display.getWidth(); // deprecated
		int height = display.getHeight();

		paint.setAntiAlias(true);
		paint.setFilterBitmap(true);
		paint.setDither(true);
		Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
		Canvas canvas = new Canvas(bmp);
		view.setDrawingCacheEnabled(true);
		view.measure(MeasureSpec.makeMeasureSpec(canvas.getWidth(), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(canvas.getHeight(), MeasureSpec.EXACTLY));
		view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
		canvas.drawBitmap(view.getDrawingCache(), 0, 0, paint);
		view.setDrawingCacheEnabled(false);
		return bmp;
	}

	public static String[] getNamefileAsset(Context context, String foldername) {
		final AssetManager assetManager = context.getAssets();
		String[] filelist = null;
		try {
			filelist = assetManager.list(foldername);
			if (filelist == null) {
			} else {
				for (int i = 0; i < filelist.length; i++) {
					String filename = filelist[i];
//					Log.e("asset", filename);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return filelist;
	}

	public static Bitmap getBitmapFromAsset(Context context, String filePath) {
		AssetManager assetManager = context.getAssets();

		InputStream istr;
		Bitmap bitmap = null;
		try {
			istr = assetManager.open(filePath);
			bitmap = BitmapFactory.decodeStream(istr);
		} catch (IOException e) {
			// handle exception
		}

		return bitmap;
	}
}
